<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\BeforeValidException;
use think\Image;
// 应用公共文件
use think\facade\Db;

/*初始化JSON*/
function dyajaxReturn($errcode=0, $message='', $data = null ,$dyurl='',$count='',$extend = null){
    $res['errcode'] = $errcode;
    $res['message'] = $message;
    if (is_null($data) == false) {
        $res['data'] = $data;
    }
    if (is_null($count) == false) {
        $res['count'] = $count;
    }
    if (is_null($extend) == false) {
        $res['extend'] = $extend;
    }
    $dyurl && $res['dyurl'] = $dyurl;
    return ajaxReturn($res);
}

function ajaxReturn($data){
    exit(json_encode($data, JSON_UNESCAPED_UNICODE));
}


//获取SystemMenuIdStr
function getIdStr($vo){
    $arr = explode('@',$vo);
    return $arr[0].'_'.$arr[1];
}


//后台用户md5加密
//function encrypt($str,$ec_salt){
//    //config("AUTH_CODE")
//    return md5($str.$ec_salt);
//}



/*
*单张图片上传
@param $filenames  文件域
@param $position  存放目录
*/
function dyuploadimg($filenames,$position='')
{
    if(IS_POST){
        $state = '';
        $position = $position.'/';
        $file = array(request()->file($filenames));
        $imgurl = '';
        //图片
        $ext = 'jpg,png,gif,jpeg,bmp';//gif|png|jpg|bmp|jpeg
        $maxsize = config('webconfig')['cfg_max_img_size'];//文件大小
        $extmsg = '图片';
        foreach($file as $key=>$val){
            if ($val) {
                if($val->getSize() > $maxsize) $state = '上传失败,'.$extmsg.'超出大小,请选择'.floor($maxsize/1024/1024) . 'MB以内的文件。';
                $originalName = strtolower($val->getOriginalName());
                if(strstr($originalName,'.php') || strstr($originalName,'.js')) $state = $extmsg.'格式错误';
                $extension = strtolower($val->extension());
                if(!in_array($extension,explode(',',$ext))) $state = '仅可上传'.$extmsg.'文件';
                if($state) return dyajaxReturn(0, $state);
                $savename = md5(mt_rand()).'.'.$val->extension();
                //$filepath = $position.date('Y/m-d').'/';
                $filepath = date('Y/m-d').'/';
                $file_path = UPLOAD_PATH.$filepath;
                if (!($_exists = file_exists($file_path))) @mkdir($file_path,0777,true);
                \think\facade\Filesystem::disk('public')->putFileAs($filepath, $val,$savename);
                $pic_path = UPLOAD_PATH.$filepath.$savename;
                @chmod($pic_path,0755);
                $pic_path = '/'.$pic_path;
            }
            $imgurl .= $pic_path.',';
        }
        $imgurl = rtrim($imgurl,',');
        if($imgurl) return dyajaxReturn(1, $extmsg.'上传成功', $imgurl);
        return dyajaxReturn(0, $extmsg.'上传失败');
    }
}

/**
*单张图片上传 缩略图
@param $filenames  文件域
@param $position  存放目录
*/
function msuploadimg($filenames,$position='')
{
    $return =[
        'code'=>0,
        'msg'=>'',
        'data'=>[]
    ];
    if(IS_POST){
        $state = '';
        $position = $position.'/';
        $file = array(request()->file($filenames));
        $imgurl = '';
        //图片
        $ext = 'jpg,png,gif,jpeg';
        $maxsize = config('image_upload_limit_size');//默认值为1MB
        $extmsg = '图片';
        foreach($file as $key=>$val){
            if ($val) {
                if($val->getSize() > $maxsize) $state = '上传失败,'.$extmsg.'超出大小,请选择'.floor($maxsize/1024/1024) . 'MB以内的文件。';
                $originalName = strtolower($val->getOriginalName());
                if(strstr($originalName,'.php') || strstr($originalName,'.js')) $state = $extmsg.'格式错误';
                $extension = strtolower($val->extension());
                if(!in_array($extension,explode(',',$ext))) $state = '仅可上传'.$extmsg.'文件';
                if($state) return dyajaxReturn(0, $state);
                $savename = md5(mt_rand()).'.'.$val->extension();
                $filepath = $position.date('Y/m-d').'/';
                $file_path = UPLOAD_PATH.$filepath;
                if (!($_exists = file_exists($file_path))) @mkdir($file_path,0777,true);
                \think\facade\Filesystem::disk('public')->putFileAs($filepath, $val,$savename);
                $pic_path = UPLOAD_PATH.$filepath.$savename;
                @chmod($pic_path,0755);
                $pic_path = '/'.$pic_path;
            }
            $imgurl .= $pic_path.',';
        }
        $imgurl = rtrim($imgurl,',');
        if(!$imgurl){
            $return['msg'] = $extmsg.'上传失败';
            return $return;
        }

        // 原图路径
        $sourcePath = app()->getRootPath()."public".$imgurl; // 原图路径
        // 目标图片路径
        $savename2 = md5(mt_rand()).date("s").'.'.$val->extension();
        $thumb_imgurl = UPLOAD_PATH.$filepath.$savename2;
        $targetPath = app()->getRootPath()."public/".$thumb_imgurl; // 压缩后保存路径
        thumb($sourcePath,$targetPath,200,200);
        //删除原图
        unlink($sourcePath);

        $return['code'] = 1;
        $return['msg'] = $extmsg.'上传成功';
        $arr['ext'] = $val->extension();
        $arr['size'] = $val->getSize();
        $arr['imgurl'] = "/".$thumb_imgurl;
        $return['data'] = $arr;
        return $return;
    }
}

/**
 * 压缩图片
 * $sourceFile 原图
 * $destinationFile 压缩图片
 * $targetWidth 宽度
 * $targetHeight 高度
 */
function thumb($sourcePath,$targetPath,$targetWidth,$targetHeight){
    // 创建Image对象
    $image = Image::open($sourcePath);
    // 按比例压缩图片
    $image->thumb($targetWidth, $targetHeight, Image::THUMB_SCALING)->save($targetPath);
}

/*
*单张图片上传，没返回
@param $filenames  文件域
@param $position  存放目录
*/
function dyuploadimgNoReturn($filenames,$position='')
{
    if(IS_POST){
        $state = '';
        $position = $position.'/';
        $file = array(request()->file($filenames));
        $imgurl = '';
        //图片
        $ext = 'jpg,png,gif,jpeg,bmp';//gif|png|jpg|bmp|jpeg
        $maxsize = config('webconfig')['cfg_max_img_size'];//文件大小
        $extmsg = '图片';
        foreach($file as $key=>$val){
            if ($val) {
                if($val->getSize() > $maxsize) $state = '上传失败,'.$extmsg.'超出大小,请选择'.floor($maxsize/1024/1024) . 'MB以内的文件。';
                $originalName = strtolower($val->getOriginalName());
                if(strstr($originalName,'.php') || strstr($originalName,'.js')) $state = $extmsg.'格式错误';
                $extension = strtolower($val->extension());
                if(!in_array($extension,explode(',',$ext))) $state = '仅可上传'.$extmsg.'文件';
                if($state) return dyajaxReturn(0, $state);
                $savename = md5(mt_rand()).'.'.$val->extension();
                //$filepath = $position.date('Y/m-d').'/';
                $filepath = date('Y/m-d').'/';
                $file_path = UPLOAD_PATH.$filepath;
                if (!($_exists = file_exists($file_path))) @mkdir($file_path,0777,true);
                \think\facade\Filesystem::disk('public')->putFileAs($filepath, $val,$savename);
                $pic_path = UPLOAD_PATH.$filepath.$savename;
                @chmod($pic_path,0755);
                $pic_path = '/'.$pic_path;
            }
            $imgurl .= $pic_path.',';
        }
        $imgurl = rtrim($imgurl,',');
        $arr = [
            'code'=>1,
            'msg'=>$extmsg.'上传成功',
            'imgurl'=>$imgurl
        ];

        if($imgurl) return $arr;
        return [
            'code'=>0,
            'msg'=>$extmsg.'上传失败'
        ];
    }
}

/*
*单张文件上传
@param $filenames  文件域
@param $position  存放目录
*/
function dyuploadfile($filenames,$position='')
{
    if(IS_POST){
        $state = '';
        //$position = $position.'/';
        $file = array(request()->file($filenames));
        $imgurl = '';
        //文件
        //$ext = 'jpg,png,gif,jpeg,txt,pdf,doc,docx,xlsx,xls';//zip|gz|rar|iso|doc|xls|ppt|wps|txt|docx
        $ext = 'zip,gz,rar,iso,doc,xls,xlsx,ppt,wps,txt,docx,pdf';
        $maxsize = config('webconfig')['cfg_max_file_size'];//文件大小
        $extmsg = 'zip,gz,rar,iso,doc,xls,xlsx,ppt,wps,txt,docx,pdf';
        foreach($file as $key=>$val){
            if ($val) {
                if($val->getSize() > $maxsize) $state = '上传失败,'.$extmsg.'超出大小,请选择'.floor($maxsize/1024/1024) . 'MB以内的文件。';
                $originalName = strtolower($val->getOriginalName());
                if(strstr($originalName,'.php') || strstr($originalName,'.js')) $state = $extmsg.'格式错误';
                $extension = strtolower($val->extension());
                if(!in_array($extension,explode(',',$ext))) $state = '仅可上传'.$extmsg.'文件';
                if($state) return dyajaxReturn(0, $state);
                $savename = md5(mt_rand()).'.'.$val->extension();
                //$filepath = $position.date('Y/m-d').'/';
                $filepath = date('Y/m-d').'/';
                $file_path = UPLOAD_PATH.$filepath;
                if (!($_exists = file_exists($file_path))) @mkdir($file_path,0777,true);
                \think\facade\Filesystem::disk('public')->putFileAs($filepath, $val,$savename);
                $pic_path = UPLOAD_PATH.$filepath.$savename;
                @chmod($pic_path,0755);
                $pic_path = '/'.$pic_path;
            }
            $imgurl .= $pic_path.',';
        }
        $imgurl = rtrim($imgurl,',');
        $ext = 'txt,pdf,doc,docx,xlsx,xls';
        $ext_arr = explode(',',$ext);
        if(in_array($val->extension(),$ext_arr)){
            $ext = 'file';
        }else{
            $ext = 'img';
        }

        if($imgurl) return dyajaxReturn(1, $extmsg.'上传成功', $imgurl,$savename,$ext);
        return dyajaxReturn(0, $extmsg.'上传失败');
    }
}

/*
*单张文件上传
@param $filenames  文件域
@param $position  存放目录
*/
function dyuploadlayedit($filenames,$position='')
{
    if(IS_POST){
        $state = '';
        //$position = $position.'/';
        $file = array(request()->file($filenames));
        $imgurl = '';
        //文件
        $ext = 'jpg,png,gif,jpeg,txt,pdf,doc,docx,xlsx,xls';
        $maxsize = config('image_upload_limit_size');//文件大小
        $extmsg = '文件';
        foreach($file as $key=>$val){
            if ($val) {
                if($val->getSize() > $maxsize) $state = '上传失败,'.$extmsg.'超出大小,请选择'.floor($maxsize/1024/1024) . 'MB以内的文件。';
                $originalName = strtolower($val->getOriginalName());
                if(strstr($originalName,'.php') || strstr($originalName,'.js')) $state = $extmsg.'格式错误';
                $extension = strtolower($val->extension());
                if(!in_array($extension,explode(',',$ext))) $state = '仅可上传'.$extmsg.'文件';
                if($state) return dyajaxReturn(0, $state);
                $savename = md5(mt_rand()).'.'.$val->extension();
                //$filepath = $position.date('Y/m-d').'/';
                $filepath = date('Y/m-d').'/';
                $file_path = UPLOAD_PATH.$filepath;
                if (!($_exists = file_exists($file_path))) @mkdir($file_path,0777,true);
                \think\facade\Filesystem::disk('public')->putFileAs($filepath, $val,$savename);
                $pic_path = UPLOAD_PATH.$filepath.$savename;
                @chmod($pic_path,0755);
                $pic_path = '/'.$pic_path;
            }
            $imgurl .= $pic_path.',';
        }
        $imgurl = rtrim($imgurl,',');
        $ext = 'txt,pdf,doc,docx,xlsx,xls';
        $ext_arr = explode(',',$ext);
        if(in_array($val->extension(),$ext_arr)){
            $ext = 'file';
        }else{
            $ext = 'img';
        }

//        if($imgurl) return dyajaxReturn(1, $extmsg.'上传成功', $imgurl,$savename,$ext);
//        return dyajaxReturn(0, $extmsg.'上传失败');
        $arr = [
            'code'=>0,
            "msg"=>"",
            "data"=>[
                "src"=>$imgurl,
                "title"=>"图片"
            ]
        ];
        return json_encode($arr, JSON_UNESCAPED_UNICODE);
    }
}



/**
 * 视频上传
 */
function dyuploadvideo($filenames,$position='')
{
    if(IS_POST){
        $state = '';
        $position = $position.'/';
        $file = request()->file($filenames);
        $videourl = '';
        //图片
        //$ext = 'mp4';
        $ext = 'swf,flv,mpg,mp3,mp4,rm,rmvb,wmv,wma,wav,ogg';
        $maxsize = config('webconfig')['cfg_max_video_size'];//文件大小
        $extmsg = '视频';
        if($file->getSize() > $maxsize) $state = '上传失败,'.$extmsg.'超出大小,请选择'.floor($maxsize/1024/1024) . 'MB以内的文件。';
        $originalName = strtolower($file->getOriginalName());
        if(strstr($originalName,'.php') || strstr($originalName,'.js')) $state = $extmsg.'格式错误';
        $extension = strtolower($file->extension());
        if(!in_array($extension,explode(',',$ext))) $state = '仅可上传'.$extmsg.'文件';
        if($state) return dyajaxReturn(0, $state);
        $savename = md5(mt_rand()).'.'.$file->extension();
        //$filepath = $position.date('Y/m-d').'/';
        $filepath = date('Y/m-d').'/';
        $file_path = UPLOAD_PATH.$filepath;
        if (!($_exists = file_exists($file_path))) @mkdir($file_path,0777,true);
        \think\facade\Filesystem::disk('public')->putFileAs($filepath, $file,$savename);
        $pic_path = UPLOAD_PATH.$filepath.$savename;
        @chmod($pic_path,0755);
        $videourl = '/'.$pic_path;
        if($videourl) return dyajaxReturn(1, $extmsg.'上传成功', $videourl);
        return dyajaxReturn(0, $extmsg.'上传失败');
    }
}

//搜索一个文件夹
//返回文件夹下的  文件 和文件夹
function GetFiles($dir){
    $files_res = array_map ( 'basename', glob ( $dir . '*') );
    if ($files_res === FALSE || ! file_exists ( $dir )) {
//        $this->error('插件目录不可读或者不存在');
//        return FALSE;
        return dyajaxReturn(0, '插件目录不可读或者不存在');
    }
    //dump($files_res);
    $arr = array();
    foreach($files_res as $k=>$v){
        $arr[$k]['name'] = $v;
        $filename = $dir.$v;
        //判断是文件夹 还是 文件
        if(is_dir($filename)){
            $arr[$k]['type'] = 'dir';
            $arr[$k]['filesize'] = '-';
        }
        if(is_file($filename)){
            $arr[$k]['type'] = 'file';

            $size = filesize($filename).'kb';

            $arr[$k]['filesize'] = $size;
        }
        //修改时间
        $updatetime = filemtime($filename);
        $arr[$k]['uptime'] = date('Y-m-d H:i:s',$updatetime);
    }

    return $arr;
}


/**
 * 删除目录及目录下所有文件或删除指定文件
 * @param str $path   待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 */
function delDirAndFile( $dirName )
{
    if ( $handle = opendir( "$dirName" ) ) {
        while ( false !== ( $item = readdir( $handle ) ) ) {
            if ( $item != "." && $item != ".." ) {
                if ( is_dir( "$dirName/$item" ) ) {
                    delDirAndFile( "$dirName/$item" );
                } else {
                    if( unlink( "$dirName/$item" ) )echo "成功删除文件： $dirName/$item\n";
                }
            }
        }
        closedir( $handle );
        if( rmdir( $dirName ) )echo "成功删除目录： $dirName\n";
    }
}


//获取指定文件夹的文件名称
function getDirContent($dir,$is_dir=false){
    $root_path = app()->getRootPath();
    $dir = $root_path .$dir;
    //搜索一个文件夹，返回这个文件夹下的所有文件
    $res = GetFiles($dir);
    $files = array();
    //取出所有文件
    foreach($res as $k=>$v){
        if($v['type'] == 'dir'){
            $dir2 = $dir.$v['name'].'/';
            $res2 = GetFiles($dir2);
            foreach($res2 as $k2=>$v2){
                if($v2['type'] == 'file'){
                    $arr1=explode('.',$v2['name']);
                    if($is_dir){
                        array_push($files,$v['name'].'/'.$arr1[0]);
                    }else{
                        array_push($files,$arr1[0]);
                    }

                }
            }
        }
        if($v['type'] == 'file'){
            $arr2=explode('.',$v['name']);
            array_push($files,$arr2[0]);
        }
    }
    return $files;
}



function getFileCode($file,$fname=''){
    $dir = ROOT_PATH .'/template/';

    if($fname){
        $file_path = $dir.$fname.'/'.$file;
    }else{
        $file_path = $dir.$file;
    }

    if(file_exists($file_path)){
        $fp = fopen($file_path,"r");
        if(filesize($file_path) == 0){
            $str = '';
        }else{
            $str = htmlspecialchars(trim(fread($fp,filesize($file_path))));//指定读取大小，这里把整个文件内容读取出来
        }
    }
    return $str;
}

/**
 * 求子集
 */
function getChildId($id,$is_false = false){
    $res = getId($id,$str='');
    $arr = explode(',',rtrim($res,','));
    $arr = array_unique($arr);
    $str = implode(",", $arr);
    //加入当前id
    if($is_false){
        $str_arr = explode(',',$str);
        if(count($str_arr) > 0){
            array_push($str_arr,$id);
            $str = implode(',',$str_arr);
        }
    }
    $str = trim($str,',');
    return $str;
}
function getId($id,$str = ''){
    $res = DB::name('category')->field('id,arrparentid')->where('parentid',$id)->select();
    foreach($res as $v){
        $str .= $v['id'] .',';
        if( count(explode(",",$v['arrparentid'])) <=2){ //向下查两层
            $jie = getId($v['id'],$str);
            $str.= $jie;
        }
    }
    return $str;
}

/*
 * 获取排列序号
 *
 * @access  public
 * @param   $tbname   string  获取该表的最大ID
 * @return  $orderid  int     返回当前ID
*/
function GetOrderID($tbname)
{
    $max = Db::name($tbname)->max('orderid');
    $orderid = (empty($max ) ? 1 : ($max  + 1));
    return $orderid;
}


if (!function_exists('gourl')) {
    /**
     * 获取url
     * @param bool $http true url
     * @param is_href 是否有href
     * @param is_html 是否用后端的指定标签
     * @return string
     */
    function gourl($url,$catdir='',$catid,$id=0,$is_href=false,$is_html=2) {
        $gourl = '';
        $domain = request()->domain();
        $pid = getPid($catid);
        $cate = DB::name('category')->where('id',$catid)->find();
        $p = DB::name('category')->where('id',$pid)->find();

        if($catdir) {
            $htmlname = $catdir;
        }else{
            if (!(empty($cate['htmlname']) || is_null($cate['htmlname']))) {
                $htmlname = $cate['htmlname'];
            } else {
                if (empty($p['htmlname']) || is_null($p['htmlname'])) {
                    $htmlname = $p['module'];
                    $is_html = 2;
                } else {
                    $htmlname = $p['htmlname'];
                }
            }
        }

        if($url == ''){

            if($id){
                if($is_href) {
                    if($is_html == 1){
                        $gourl .= 'href="' . $domain . '/' . $htmlname . 'detail.html?catid='.$catid.'&id='.$id.'"';
                    }else {
                        $gourl .= 'href="' . $domain . '/' . $htmlname . '-' . $catid . '-' . $id . '-1.html"';
                    }
                }else{
                    //$gourl .= $domain . '/' . $catdir . '-' . $catid . '-' . $id . '-1.html';
                    if($is_html == 1){
                        $gourl .= $domain . '/' . $htmlname .'detail.html?catid='.$catid.'&id='.$id;
                    }else {
                        $gourl .= $domain . '/' . $htmlname . '-' . $catid . '-' . $id . '-1.html';
                    }
                }
            }else{
                if($is_href) {
                    if($is_html == 1){
                        if($cate['parentid'] == 0) {
                            $gourl .= 'href="' . $domain . '/' . $htmlname . '.html"';
                        }else{
                            $gourl .= 'href="' . $domain . '/' . $htmlname . '.html?catid=' . $catid . '"';
                        }
                    }else {
                        $gourl .= 'href="' . $domain . '/' . $htmlname . '-' . $catid . '-1.html"';
                    }
                }else{
                    //$gourl .= $domain . '/' . $catdir . '-' . $catid . '-1.html';
                    if($is_html == 1){
                        $gourl .= $domain . '/' . $htmlname .'html?catid='.$catid;
                    }else {
                        $gourl .= $domain . '/' . $htmlname . '-' . $catid . '-1.html';
                    }
                }
            }
        }else{
            if($is_href) {
                $gourl .= 'href="' . $url . '" target="_self"';
            }else{
                $gourl .=  $url . '" target="_self';
            }
        }
        return $gourl;
    }
}

function goOnlyUrl($url,$catdir='',$catid,$id=0){
    $gourl = '';
    $domain = request()->domain();
    if($catdir == ''){
        $pid = getPid($catid);
        $p = DB::name('category')->where('id',$pid)->find();
        if($url == ''){
            if($id){
                $gourl .=  $domain . '/' . $p['catdir'] . 'detail.html?catid='.$catid.'&id='.$id;
                //$gourl .= $domain.'/'.$p['catdir'].'-'.$catid.'-'.$id.'-1.html';
            }else{
                //$gourl .= $domain.'/'.$p['catdir'].'-'.$catid.'-1.html';
                $gourl .=  $domain . '/' . $p['catdir'] . '.html?catid=' . $catid ;
            }
        }else{
            $gourl .= $url.'" target="_self';
        }
    }else{
        if($url == ''){
            if($id){
                //$gourl .= $domain.'/'.$catdir.'-'.$catid.'-'.$id.'-1.html';
                $gourl .=  $domain . '/' . $catdir . '.html?catid='.$catid.'&id='.$id;
            }else{
                //$gourl .= $domain.'/'.$catdir.'-'.$catid.'-1.html';
                $gourl .=  $domain . '/' . $catdir . '.html?catid=' . $catid ;
            }
        }else{
            $gourl .= $url.'" target="_self';
        }
    }
    return $gourl;
}


if (!function_exists('getPid')) {
    /**
     * 获取父级
     * @param bool $http true url
     * @return string
     */
    function getPid($catid) {
        $pid='';
        if($catid != ''){
            $r = DB::name('category')->where('id',$catid)->find();
            if($r['parentid'] == 0){
                $pid = $catid;
            }else{
                $mid = DB::name('category')->where('id',$r['parentid'])->find();
                //$middle = $mid['id'];
                if($mid['parentid'] == 0 ){
                    $pid = $mid['id'];
                }else{
                    $pid = $mid['parentid'];
                }
            }
        }
        return $pid;
    }
}


function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "") {
    $header = empty($header) ? '' : $header;
    //支持json数据数据提交
    if($data_type == 'json'){
        $post_string = json_encode($post_data);
    }elseif($data_type == 'array') {
        $post_string = $post_data;
    }elseif(is_array($post_data)){
        $post_string = http_build_query($post_data, '', '&');
    }
    $ch = curl_init();    // 启动一个CURL会话
    curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"); // 模拟用户使用的浏览器
    //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
    $result = curl_exec($ch);

    // 打印请求的header信息
//        $a = curl_getinfo($ch);
//        var_dump($a);

    curl_close($ch);
    return $result;
}

function curlGet($url){
//        $header = array(
//            'Accept: application/json',
//            'Access-Token:'.$access_token
//        );
    $header = array(
        'Accept: application/json',
    );
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 超时设置,以秒为单位
    curl_setopt($curl, CURLOPT_TIMEOUT, 1);
    // 超时设置，以毫秒为单位
    // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
    // 设置请求头
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    //执行命令
    $data = curl_exec($curl);
    // 显示错误信息
    if (curl_error($curl)) {
        print "Error: " . curl_error($curl);
    } else {
        // 打印返回的内容
        //        var_dump($data);
        curl_close($curl);
        return $data;
    }
}


/**
 * 生成token
 * $uid 输入用户openid&&id
 */

if (!function_exists('signToken')) {
    //生成验签
    function signToken($uid)
    {
        $key = '!@#$%*&';         //这里是自定义的一个随机字串，应该写在config文件中的，解密时也会用，相当    于加密中常用的 盐  salt
        $token = array(
            "iss" => '',         	//签发者 可以为空
            "aud" => '',         	//面象的用户，可以为空
            "iat" => time(),      	//签发时间
            "nbf" => time() + 3,      	//在什么时候jwt开始生效  （这里表示生成100秒后才生效）
            "exp" => time() + 43200, //token 过期时间
            'data' => $uid			//记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
        );
        $jwt = JWT::encode($token, $key, "HS256");  //根据参数生成了 token
        return $jwt;
    }
}
/**
 * 验证token
 * $token 生成的token值
 */

if (!function_exists('checkToken')) {
    //验证token
    function checkToken($token)
    {
        $key = '!@#$%*&';
        $status = array("code" => 2);

        try {
            JWT::$leeway = 60; //当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key($key, 'HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            $res['code'] = 1;
            $res['msg'] = '';
            $res['data'] = $arr['data'];
            return $res;
        } catch (SignatureInvalidException $e) { //签名不正确
            $status['msg'] = "签名不正确";
            return $status;
        } catch (BeforeValidException $e) { // 签名在某个时间点之后才能用
            $status['msg'] = "token未生效";
            return $status;
        } catch (ExpiredException $e) { // token过期
            $status['msg'] = "token失效";
            return $status;
        } catch (Exception $e) { //其他错误
            $status['msg'] = "toekn未知错误";
            return $status;
        }
    }
}


//判断是pc还是mobile
if(!function_exists('isMobile')) {
    function isMobile()
    {
        $useragent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $useragent_commentsblock = preg_match('|\(.*?\)|', $useragent, $matches) > 0 ? $matches[0] : '';
        function CheckSubstrs($substrs, $text)
        {
            foreach ($substrs as $substr)
                if (false !== strpos($text, $substr)) {
                    return true;
                }
            return false;
        }

        $mobile_os_list = array('Google Wireless Transcoder', 'Windows CE', 'WindowsCE', 'Symbian', 'Android', 'armv6l', 'armv5', 'Mobile', 'CentOS', 'mowser', 'AvantGo', 'Opera Mobi', 'J2ME/MIDP', 'Smartphone', 'Go.Web', 'Palm', 'iPAQ');
        $mobile_token_list = array('Profile/MIDP', 'Configuration/CLDC-', '160×160', '176×220', '240×240', '240×320', '320×240', 'UP.Browser', 'UP.Link', 'SymbianOS', 'PalmOS', 'PocketPC', 'SonyEricsson', 'Nokia', 'BlackBerry', 'Vodafone', 'BenQ', 'Novarra-Vision', 'Iris', 'NetFront', 'HTC_', 'Xda_', 'SAMSUNG-SGH', 'Wapaka', 'DoCoMo', 'iPhone', 'iPod');

        $found_mobile = CheckSubstrs($mobile_os_list, $useragent_commentsblock) ||
            CheckSubstrs($mobile_token_list, $useragent);

        if ($found_mobile) {
            return true;
        } else {
            return false;
        }
    }
}


/**
 * 获取IP
 */
function get_client_ip($type = 0, $adv = false) {
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip [$type];
    if ($adv) {
        if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) {
            $arr = explode ( ',', $_SERVER ['HTTP_X_FORWARDED_FOR'] );
            $pos = array_search ( 'unknown', $arr );
            if (false !== $pos)
                unset ( $arr [$pos] );
            $ip = trim ( $arr [0] );
        } elseif (isset ( $_SERVER ['HTTP_CLIENT_IP'] )) {
            $ip = $_SERVER ['HTTP_CLIENT_IP'];
        } elseif (isset ( $_SERVER ['REMOTE_ADDR'] )) {
            $ip = $_SERVER ['REMOTE_ADDR'];
        }
    } elseif (isset ( $_SERVER ['REMOTE_ADDR'] )) {
        $ip = $_SERVER ['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf ( "%u", ip2long ( $ip ) );
    $ip = $long ? array (
        $ip,
        $long
    ) : array (
        '0.0.0.0',
        0
    );
    return $ip [$type];
}


/*去除微信昵称特殊的表情符*/

function filterEmoji($str)

{

    $str = preg_replace_callback('/./u',

        function (array $match) {

            return strlen($match[0]) >= 4 ? '' : $match[0];

        },

        $str);

    return $str;

}

//单页获取
if(!function_exists('getPage')) {
    function getPage($id,$tablename,$field='')
    {
        if($field){
            $info = DB::name($tablename)->where('id','=',$id)->field($field)->find();
            $info = $info[$field];
        }else{
            $info = DB::name($tablename)->where('id','=',$id)->find();
        }
        return $info;
    }
}



//获取title 和 mate 值
if(!function_exists('GetHeader')) {
    function GetHeader($sid = 1, $cid = 0, $id = 0, $str = '')
    {

        //检查站点标识
        if ($sid != 1) {
            $webconfig = DB::name("webconfig")
                ->where('siteid','=',$sid)
                ->select();
            $webconfig_arr = [];
            foreach($webconfig as $v){
                $webconfig_arr[$v['varname']] = $v['varvalue'];
            }
            $r = DB::name('site')->where('id',$sid)->find();
            if (isset($r['sitekey'])) {
                /*
                $cfg_webname = config('cfg_webname_'.$r['sitekey']);
                $cfg_generator = config('cfg_generator_'.$r['sitekey']);
                $cfg_author = config('cfg_author_'.$r['sitekey']);
                $cfg_keyword = config('cfg_keyword_'.$r['sitekey']);
                $cfg_description = config('cfg_description_'.$r['sitekey']);
                */
                $cfg_webname = $webconfig_arr['cfg_webname'.$r['sitekey']];
                $cfg_generator = $webconfig_arr['cfg_generator'.$r['sitekey']];
                $cfg_author = $webconfig_arr['cfg_author'.$r['sitekey']];
                $cfg_keyword = $webconfig_arr['cfg_keyword'.$r['sitekey']];
                $cfg_description = $webconfig_arr['cfg_description'.$r['sitekey']];
            }
        }else{
            $webconfig = DB::name("webconfig")
                ->where('siteid','=',1)
                ->select();
            $webconfig_arr = [];
            foreach($webconfig as $v){
                $webconfig_arr[$v['varname']] = $v['varvalue'];
            }

            $cfg_webname = $webconfig_arr['cfg_webname'];
            $cfg_generator = $webconfig_arr['cfg_generator'];
            $cfg_author = $webconfig_arr['cfg_author'];
            $cfg_keyword = $webconfig_arr['cfg_keyword'];
            $cfg_description = $webconfig_arr['cfg_description'];

        }

        //设置了自定义标题
        if ($str != '') {
            $header_str = '<title>' . $str . ' - ' . $cfg_webname . '</title>' . "\n";
            $header_str .= '<meta name="generator" content="' . $cfg_generator . '" />' . "\n";
            $header_str .= '<meta name="author" content="' . $cfg_author . '" />' . "\n";
            $header_str .= '<meta name="keywords" content="' . $cfg_keyword . '" />' . "\n";
            $header_str .= '<meta name="description" content="' . $cfg_description . '" />' . "\n";
        } else {
            //显示详细信息
            if (!empty($cid) && !empty($id)) {
                //$r = $dosql->GetOne("SELECT * FROM `#@__infoclass` WHERE `id`=$cid");
                $r = DB::name('category')->where('id',$cid)->find();
                $tbname = $r['module'];

                //获取栏目信息
                //$r2 = $dosql->GetOne("SELECT * FROM `$tbname` WHERE `id`=$id");
                $r2 = DB::name($tbname)->where('id',$id)->find();

                $header_str = '<title>';

                if (isset($r2['title']))
                    $header_str .= $r2['title'] . ' - ';

                if (isset($r['catname']))
                    $header_str .= $r['catname'];

                $header_str .= ' - ' . $cfg_webname . '</title>' . "\n";
                //$header_str .= '<meta name="generator" content="' . $cfg_generator . '" />' . "\n";
                $header_str .= '<meta name="author" content="' . $cfg_author . '" />' . "\n";
                $header_str .= '<meta name="keywords" content="';

                if (isset($r2['keywords']) && $r2['keywords']!='')
                    $header_str .= $r2['keywords'];
                else
                    $header_str .= $cfg_keyword;

                $header_str .= '" />' . "\n";
                $header_str .= '<meta name="description" content="';

                if (isset($r2['description']) && $r2['description']!='')
                    $header_str .= $r2['description'];
                else
                    $header_str .= $cfg_description;

                $header_str .= '" />' . "\n";

            } //显示栏目信息
            else if (!empty($cid)) {
                //$r = $dosql->GetOne("SELECT * FROM `#@__infoclass` WHERE `id`=$cid");
                $r = DB::name('category')->where('id',$cid)->find();

                $header_str = '<title>';

                if (!empty($r['title']))
                    $header_str .= $r['title'];
                else if (!empty($r['catname']))
                    $header_str .= $r['catname'] . ' - ' . $cfg_webname;
                else
                    $header_str .= $cfg_webname;

                $header_str .= '</title>' . "\n";
                //$header_str .= '<meta name="generator" content="' . $cfg_generator . '" />' . "\n";
                $header_str .= '<meta name="author" content="' . $cfg_author . '" />' . "\n";
                $header_str .= '<meta name="keywords" content="';

                if (!empty($r['keywords']))
                    $header_str .= $r['keywords'];
                else
                    $header_str .= $cfg_keyword;

                $header_str .= '" />' . "\n";
                $header_str .= '<meta name="description" content="';

                if (!empty($r['description']))
                    $header_str .= $r['description'];
                else
                    $header_str .= $cfg_description;

                $header_str .= '" />' . "\n";
            } //显示站点信息
            else {
                $header_str = '<title>' . $cfg_webname . '</title>' . "\n";
                //$header_str .= '<meta name="generator" content="' . $cfg_generator . '" />' . "\n";
                $header_str .= '<meta name="author" content="' . $cfg_author . '" />' . "\n";
                $header_str .= '<meta name="keywords" content="' . $cfg_keyword . '" />' . "\n";
                $header_str .= '<meta name="description" content="' . $cfg_description . '" />' . "\n";
            }
        }

        return $header_str;
    }
}


function GetApiHeader($sid = 1, $cid = 0, $id = 0, $str = ''){
    if ($sid != 1) {
        $webconfig = DB::name("webconfig")
            ->where('siteid','=',$sid)
            ->select();
        $webconfig_arr = [];
        foreach($webconfig as $v){
            $webconfig_arr[$v['varname']] = $v['varvalue'];
        }
        $r = DB::name('site')->where('id',$sid)->find();
        if (isset($r['sitekey'])) {
            $cfg_webname = $webconfig_arr['cfg_webname'.$r['sitekey']];
            $cfg_generator = $webconfig_arr['cfg_generator'.$r['sitekey']];
            $cfg_author = $webconfig_arr['cfg_author'.$r['sitekey']];
            $cfg_keyword = $webconfig_arr['cfg_keyword'.$r['sitekey']];
            $cfg_description = $webconfig_arr['cfg_description'.$r['sitekey']];
        }
    }else{
        $webconfig = DB::name("webconfig")
            ->where('siteid','=',1)
            ->select();
        $webconfig_arr = [];
        foreach($webconfig as $v){
            $webconfig_arr[$v['varname']] = $v['varvalue'];
        }

        $cfg_webname = $webconfig_arr['cfg_webname'];
        $cfg_generator = $webconfig_arr['cfg_generator'];
        $cfg_author = $webconfig_arr['cfg_author'];
        $cfg_keyword = $webconfig_arr['cfg_keyword'];
        $cfg_description = $webconfig_arr['cfg_description'];
    }
    //显示详细信息
    if (!empty($cid) && !empty($id)) {
        $r = DB::name('category')->where('id',$cid)->find();
        $tbname = $r['module'];

        //获取栏目信息
        $r2 = DB::name($tbname)->where('id',$id)->find();

        $title_str = '';
        if (isset($r2['title']))
            $title_str .= $r2['title'] . ' - ';

        if (isset($r['catname']))
            $title_str .= $r['catname'];
        $title = $title_str.' - ' . $cfg_webname;
        $author = $cfg_author;

        $keywords_str = '';
        if (isset($r2['keywords']) && $r2['keywords']!='') {
            $keywords_str .= $r2['keywords'];
        }else {
            $keywords_str .= $cfg_keyword;
        }
        $keywords = $keywords_str;

        $description_str = '';
        if (isset($r2['description']) && $r2['description']!='') {
            $description_str .= $r2['description'];
        }else {
            $description_str .= $cfg_description;
        }
        $description = $description_str;
    } //显示栏目信息
    else if (!empty($cid)) {
        $r = DB::name('category')->where('id',$cid)->find();

        $title_str = '';
        if (!empty($r['title'])){
            $title_str.= $r['title'];
        }else if (!empty($r['catname'])){
            $title_str .= $r['catname'] . ' - ' . $cfg_webname;
        }else{
            $title_str .= $cfg_webname;
        }
        $title = $title_str;
        $author = $cfg_author;
        $keywords_str = '';
        if (!empty($r['keywords'])) {
            $keywords_str .= $r['keywords'];
        }else {
            $keywords_str .= $cfg_keyword;
        }
        $keywords = $keywords_str;

        $description_str = '';
        if (!empty($r['description'])) {
            $description_str .= $r['description'];
        }else {
            $description_str .= $cfg_description;
        }
        $description = $description_str;

    } //显示站点信息
    else {
        $title = $cfg_webname;
        $author = $cfg_author;
        $keywords = $cfg_keyword;
        $description = $cfg_description;
    }
    return [
        'title'=>$title,
        'author'=>$author,
        'keywords'=>$keywords,
        'description'=>$description,
    ];
}


//敏感词过滤
function filterate($content){
    $result = [
        'code' => 0,
        'msg'    => '',
        'data'   => [],
    ];

    $webconfig = config('webconfig');
    $cfg_filterate = $webconfig['cfg_filterate'];
    //敏感词过滤
    $filterate_arr = explode(',',$cfg_filterate);
    foreach ($filterate_arr as $k=>$v){
        if(strpos($content,$v) !== false){
            $result['msg'] = '提交的内容中包含敏感词:'.$v;
            return $result;
        }
    }
    $result['code'] = 1;
    $result['msg'] = '成功';
    return $result;
}

/*function array3string($array)
{
    $string = [];
    if ($array && is_array($array)) {
        foreach ($array as $key => $value) {
            $string[] = $key . '=' . $value;
        }
    }
    return implode(',', $string);
}*/

//数组转字符串
function array3string($info) {
    if($info == '') return '';
    if(!is_array($info)){
        $string = stripslashes($info);
    }
    foreach($info as $key => $val){
        $string[$key] = stripslashes($val);
    }
    $setup = var_export($string, TRUE);
    return $setup;
}


//记录后台操作记录
function adminLog($content,$id=0){
    $data['user_id'] = session('admin_id');
    $data['admin_name'] = session('admin_user');
    $data['content'] = $content;
    $data['common_id'] = $id;
    $data['add_time'] = time();

    DB::name("admin_operate")->insert($data);
}


function addDomainToImgSrc($html, $domain) {
    // 使用正则表达式查找所有的img标签
    preg_match_all('/<img[^>]+>/i', $html, $imgTags);

    // 遍历所有的img标签
    foreach ($imgTags[0] as $index => $imgTag) {
        // 使用正则表达式查找src属性
        preg_match('/src="([^"]+)"/i', $imgTag, $match);

        // 如果找到了src属性，并且它不是一个绝对路径
        if (isset($match[1]) && !preg_match('/^(?:http|https):/', $match[1])) {
            // 给src属性加上域名
            $replacement = 'src="' . $domain . '/' . ltrim($match[1], '/') . '"';
            // 替换原来的src属性
            $html = str_replace($match[0], $replacement, $html);
        }
    }
    return $html;
}

function checkmobile($value){
    $result = [
        'code' => 0,
        'msg'    => '',
        'data'   => [],
    ];
    if(!is_numeric($value)){
        $result['msg'] = '请输入数字';
        return $result;
    }
    if(strlen($value) != 11){
        $result['msg'] = '请输入11位手机号';
        return $result;
    }
    if (!preg_match("/^1[3456789]\d{9}$/", $value)) {
        $result['msg'] = '手机号码格式不正确';
        return $result;
    }
    $result['code'] = 1;
    $result['msg'] = '手机号码正确';
    return $result;
}
